const express=require('express');
const router=express.Router();
// const {stulist}= require('../data');
// const {dMlist}= require('../data');
const PagerHelper = require('../PagerHelper');
const pager=PagerHelper.pagerHelper;
pager.href = "/stuM.html";
const lodash=require('lodash');
const dao =require('../model/stuDao');
//get post是浏览器相对位置，render 是对于服务器文W件夹的位置
let searchArgs;
 router.get("/stuM.html", async (req, res, next) => {
    //调用Promise API时，因为会在异步函数中触发错误，这类错误是app.js配置的错误中间件无法处理的
    let where = {};//查询条件对象
    if (searchArgs) {
        if (searchArgs.name) {
            where.name = RegExp(searchArgs.name, "i");
        }
        if (searchArgs.minPrice) {
            if (!where.price) {
                where.price = {};
            }
            where.price.$gte = searchArgs.minPrice
        }
        if (searchArgs.maxPrice) {
            if (!where.price) {
                where.price = {};
            }
            where.price.$lte = searchArgs.maxPrice
        }
    }
    //根据查询条件获得查询条数，成功后把条数设置给pager然后进行dao的查找
    dao.getCount(where).then(count => {
        pager.setCount(count);
        return dao.findByPage(where);
        // res.json(data);
        // res.end();
        //上述成功后,发送find的接口数据
    }).then(data => {
        pager.data = data;
    //    for (value in data)
    //     console.log(`insert into stum values(${data[value].id},'${data[value].name}','${data[value].gender}','${data[value].phone}',${data[value].dorm},'${data[value].dormroom}');`);
        res.render("stuM", {
            title: "管理员管理页面",
            username: "韦德",
            stulist: pager.data,
            pager, searchArgs
        });
    }).catch(err => {
        next(err);
    })
});

/**
 * 搜索功能
 */
router.post("/stuM.html", (req, res) => {
    if (req.body) {
        searchArgs = {};
        if (req.body.name && req.body.name.trim().length > 0) {
            searchArgs.name = req.body.name
        } else {
            delete searchArgs.name;
        }
        if (req.body.minPrice && req.body.minPrice.trim().length > 0) {
            searchArgs.minPrice = parseFloat(req.body.minPrice);
        } else {
            delete searchArgs.minPrice;
        }
        if (req.body.maxPrice && req.body.maxPrice.trim().length > 0) {
            searchArgs.maxPrice = parseFloat(req.body.maxPrice);
        } else {
            delete searchArgs.maxPrice;
        }
    }
    res.redirect("/stuM.html");
})


router.get("/del.do",(req,res,next)=>{
    // lodash.remove(stulist,value=>value.id==req.query.id);
    if(req.query._id){
        dao.deleteById(req.query._id).then(data=>res.redirect("/stuM.html")).catch(err=>next(err));
    }else{
        res.redirect("/stuM.html");
    }
});

router.get("/delBatch.do",(req,res,next)=>{;
    let idsStr = req.query.ids;
    let ids = idsStr.split(",");//得到的是一个字符串数组
    dao.deleteByIds(ids).then(data => res.redirect("/stuM.html")).catch(err => next(err));
});

router.get("/add.html",(req,res)=>{
    res.render("stuMadd",{
        title:"添加学生页面",
});
});

router.get("/edit.html",(req,res,next)=>{
    let {_id}=req.query;
    if(_id){
        dao.findById(_id).then(editObj => {
            res.render("stuMadd", {
                title: "编辑学生页面",
                editObj
            });
        }).catch(err => next(err));
    }else{
        res.redirect("/stuM.html");
    }
});

router.post("/save.do",(req,res,next)=>{
    let newObj = Object.assign({}, req.body);
    console.log(newObj);
    console.log(req.body);
    //区分添加还是编辑
    if (newObj._id) {
        //编辑
        // //引用数据类型的特点
        // Object.assign(editObj, newObj);
        dao.update(newObj, newObj._id).then(data => res.redirect("/stuM.html")).catch(err => next(err));
    } else {
        //添加
        delete newObj._id;
        // //保存到数组中
        dao.insert(newObj).then(data => res.redirect("/stuM.html")).catch(err => next(err));
    }
});

// rouget.get("/toInsert.do", (req, res) => {
//     dao.finAll().then(data=>{
//         for (let i = 0; i <data.length;i++){
//             let item = data[i];
//             let sql = `insert into stum values(${data[i].id},'${data[i].name}','${data[i].gender}','${data[i].phone}',${data[i].dorm},'${data[i].dormroom}');`
//             console.log(sql);
//         }
        
//     }).catch(err => next(err));
// })
module.exports = router;